import React from 'react';
import { connect } from 'react-redux';
import * as calcAtions from '../../../actions/calculator';


const mapStateToProps = state => ({
  result: state.calculator.result,
  expression: state.calculator.expression,
});

const mapDispatchToProps = calcAtions;

const KEYBOARD_MAP = [
  ['1', '2', '3', '+'],
  ['4', '5', '6', '-'],
  ['7', '8', '9', '*'],
  ['C', '0', '=', '/'],
];

const KEYBOARD_ACTIONS = {
  'C': 'CLEAR',
  '=': 'COMMIT',
};

const styles = {
  root: {
    fontFamily: 'monospace',
    width: 400,
    fontSize: 16,
    lineHeight: 2.5,
    fontWeight: 500,
    color: '#222',
  },
  row: {
    userSelect: 'none',
    display: 'flex',
    flexFlow: 'row nowrap',
  },
  button: {
    width: '25%',
    textAlign: 'center',
    border: '1px solid #ccc',
    cursor: 'pointer',
  },
  expression: {
    textAlign: 'right',
    background: '#444',
    color: '#fff',
    padding: 16,
    marginBottom: 8,
    lineHeight: 1.25,
  },
  result: {
    color: 'yellow'
  }
}

const Display = connect(mapStateToProps)(({ result, expression }) => (
  <>
    <span>{expression}</span>
    {result && <>
      &nbsp; = &nbsp;
      <span style={styles}>{result}</span>
    </>}
  </>
));

const Keyboard = ({ onClick }) => (
  KEYBOARD_MAP.map((row, i) => (
    <div key={`row:${i}`} style={styles.row}>
      {row.map(text => (
        <div key={text} style={styles.button} onClick={onClick} data-text={text}>
          {text}
        </div>
      ))}
    </div>
  ))
);

@connect(null, mapDispatchToProps)
class ClaculatorPage extends React.PureComponent {
  handleClick = (e) => {
    const { text } = e.currentTarget.dataset;
    const action = KEYBOARD_ACTIONS[text];
    switch (action) {
      case 'COMMIT':
        this.props.commit();
        break;

      case 'CLEAR':
        this.props.clear();
        break;

      default:
        this.props.input(text);
        break;
    }
  }
  render() {
    return (
      <div style={styles.root}>
        <div style={styles.expression}>
          &nbsp; <Display />
        </div>
        <Keyboard onClick={this.handleClick} />
      </div>
    )
  }
}

export default ClaculatorPage;